package com.nacos.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.util.Map;

public class YamlToJsonUtil {

    /**
     * @return 返回yaml文件中对应的json数据
     */
    public static String toJson() {
        try {
            String filename = "D:\\data\\IdeaProjects\\springcloud-nacos\\config001\\src\\main\\resources\\application.yml";
            // 创建Yaml对象
            Yaml yaml = new Yaml();
            FileInputStream input = new FileInputStream(filename);
            Map<String, Object> data = yaml.load(input);
            Gson gson = new Gson();
            return gson.toJson(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param filename yaml文件名称
     * @return 返回yaml文件中对应的json数据
     */
    public static JsonObject toJson(String filename) {
        try {
            // 创建Yaml对象
            Yaml yaml = new Yaml();
            FileInputStream input = new FileInputStream(filename);
            Map<String, Object> data = yaml.load(input);
            Gson gson = new Gson();
            return gson.toJsonTree(data).getAsJsonObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(toJson());
        System.out.println(toJson("D:\\data\\IdeaProjects\\springcloud-nacos\\config001\\src\\main\\resources\\application.yml"));
    }
}
